package slef.xchen;


import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author xchen
 * @date 2019-09-17 17:35
 */
public class DelayHelper {

	private static final ExecutorService INVOKER_THREAD_POOL = Executors.newScheduledThreadPool(5);
	private static final ScheduledExecutorService SCHEDULE_THREAD_POOL = Executors.newScheduledThreadPool(10);
	private static final Map<String, Turntable<?>> TABLES = new ConcurrentHashMap<>();

	static {
		SCHEDULE_THREAD_POOL.scheduleWithFixedDelay(() -> {
			for (Turntable<?> turntable : TABLES.values()) {
				List dataList = turntable.next();
				if (null == dataList) {
					continue;
				}
				INVOKER_THREAD_POOL.submit(() -> {
					try {
						turntable.getCallback().process(dataList);
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}
		}, 0, 1, TimeUnit.SECONDS);
	}

	public static <T> void register(Turntable<T> turntable) {
		if (TABLES.containsKey(turntable.getName())) {
			throw new IllegalArgumentException("所指定name的turntable已存在！");
		}
		TABLES.put(turntable.getName(), turntable);
	}

	public static <T> Turntable<T> use(String name) {
		return (Turntable<T>) TABLES.get(name);
	}

	public static void shutdown(){
		INVOKER_THREAD_POOL.shutdown();
		SCHEDULE_THREAD_POOL.shutdown();
	}

}
